<template>
  <basic-container>
    <div class="search-form">
      <el-form
        ref="form"
        :model="queryForm"
        :rules="rules"
        label-width="100px"
        style="display: flex; flex-wrap: wrap"
      >
        <el-row :gutter="20" style="width: 100%">
          <el-col :span="5" style="margin-left: -55px">
            <el-form-item label="短ID:" prop="shortId">
              <el-input placeholder="请输入短ID" size="mini" v-model="queryForm.shortId" clearable
                        @keyup.enter.native="submitForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="素材名称:" prop="name">
              <el-input placeholder="请输入素材名称" size="mini" v-model="queryForm.name" clearable
                        @keyup.enter.native="submitForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="本地文件名:" prop="localFilename">
              <el-input placeholder="请输入本地文件名" size="mini" v-model="queryForm.localFilename"
                        clearable @keyup.enter.native="submitForm">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="设计师:">
              <el-select v-model="queryForm.designer" size="mini" clearable filterable placeholder="请选择"
                         @change="submitForm">
                <el-option
                  v-for="(item,index) in designerList"
                  :key="index"
                  :label="item.realName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="4" style="min-width: 160px;display:flex;justify-content:flex-end;float: right;margin-top: 5px;margin-right: -16px">
            <el-tooltip class="item" effect="dark" content="展开全部" placement="top">
              <el-button :class="upIcon" class="search-circle" @click="unfoldIcon"
                         style="margin-right: 10px"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="清空" placement="top">
              <el-button id="id-business-offer-emptyForm" :class="emptyIcon" class="search-circle"
                         @click="resetSearch"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button id="id-business-offer-searchForm-four" type="primary" icon="el-icon-search" size="mini"
                         @click="submitForm" style="margin-right: 0">
                搜索
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="导出" placement="top">
              <el-button id="id-business-offer-export-excel" type="primary" icon="el-icon-download" size="mini"
                         @click="exportExcel" style="margin-right: 0">
                导出
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row v-show="searchConceal" :gutter="20" style="width: 100%">
          <el-col :span="5" style="margin-left: -55px">
            <el-form-item label="媒体:">
              <el-select
                size="mini"
                v-model="queryForm.platform"
                placeholder="请选择"
                clearable
                style="width: 100%"
                @change="submitForm"
              >
                <el-option
                  v-for="item in platformList"
                  :key="item.dictKey"
                  :label="item.dictValue"
                  :value="item.dictKey"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="投放地区:">
              <el-select v-model="queryForm.nationList" size="mini" multiple clearable filterable placeholder="请选择"
                         style="width: 100%"
                         @blur="submitForm">
                <el-option
                  v-for="(item,index) in nationList"
                  :key="index"
                  :label="item.dictValue"
                  :value="item.dictKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="更新时间:">
              <el-date-picker
                size="mini"
                v-model="updateDateRange"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="submitForm"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!--        <el-col :span="5">-->
          <!--          <el-form-item style="width: 280px">-->
          <!--            <el-button-->
          <!--              size="mini"-->
          <!--              type="primary"-->
          <!--              icon="el-icon-search"-->
          <!--              @click="submitForm"-->
          <!--            >搜索-->
          <!--            </el-button-->
          <!--            >-->
          <!--            <el-button size="mini" icon="el-icon-delete" @click="resetSearch"-->
          <!--            >清空-->
          <!--            </el-button-->
          <!--            >-->
          <!--          </el-form-item>-->
          <!--        </el-col>-->
        </el-row>
      </el-form>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleTabsClick">
      <el-tab-pane label="图片" name="0">
        <avue-crud
          v-if="activeName == 0"
          :option="optionImg"
          :table-loading="loading"
          :data="imageData"
          :page.sync="page"
          :permission="permissionList"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
          @sort-change="sortImageChange"
          :summary-method="summaryMethod"
        >
          <template slot="menuLeft">
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              plain
              v-if="permission.creativeperformance_delete"
              @click="handleDelete"
            >删 除
            </el-button>
          </template>
          <template slot-scope="{ row }" slot="shortId">
            <div>
              <div><a href="javascript: void(0)" style="text-decoration: underline;" @click="onCreativeTagsClick(row)">{{
                  row.shortId
                }}</a></div>
            </div>
          </template>
          <template slot-scope="{ row }" slot="creativeUrl">
            <div @click="handleMediaPreview(row)">
              <img
                v-show="dialogType(row.creativeUrl) == 'image'"
                width="100%"
                :src="row.creativeUrl"
              />
              <video
                v-show="dialogType(row.creativeUrl) == 'video'"
                :src="row.creativeUrl"
                style="width: 100%"
              ></video>
            </div>
          </template>
          <template slot-scope="{ row }" slot="designer">
            <div>
              {{ designerChange(row) }}
            </div>
          </template>
          <template slot-scope="{ row }" slot="ads">
            <div>
              {{ countAds(row) }}
            </div>
          </template>
          <template slot-scope="{ row }" slot="ctr">
            <div>{{ row.ctr }}%</div>
          </template>
          <template slot-scope="{ row }" slot="cvr">
            <div>{{ row.cvr }}%</div>
          </template>
          <template slot-scope="{ row }" slot="onlineStatus">
            <el-tag type="danger" v-if="row.status !== 2 && row.onlineStatus === 1">违规</el-tag>
            <el-tag type="success" v-else-if="row.onlineStatus === 1">在线</el-tag>
            <el-tag type="info" v-else>未在线</el-tag>
          </template>
          <template slot-scope="{type,size,row}" slot="menu">
            <el-tooltip content="查看" placement="top">
              <el-button size="small" icon="el-icon-view" type="text" @click="checkRow(row)"></el-button>
            </el-tooltip>
          </template>
          <template slot-scope="{row}" slot="impressions">
            <div>{{ thousandSeparator(row.impressions) }}</div>
          </template>
          <template slot-scope="{row}" slot="allExpend">
            <div>{{ thousandSeparator(row.allExpend) }}</div>
          </template>
          <template slot-scope="{row}" slot="install">
            <div>{{ thousandSeparator(row.install) }}</div>
          </template>
          <template slot-scope="{row}" slot="clicks">
            <div>{{ thousandSeparator(row.clicks) }}</div>
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane label="视频" name="1">
        <avue-crud
          v-if="activeName == 1"
          :option="optionVio"
          :table-loading="loading"
          :data="videoData"
          :page.sync="page"
          :permission="permissionList"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
          @sort-change="sortVideoChange"
          :summary-method="summaryMethod"
        >
          <template slot="menuLeft">
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              plain
              v-if="permission.creativeperformance_delete"
              @click="handleDelete"
            >删 除
            </el-button>
          </template>
          <template slot-scope="{ row }" slot="shortId">
            <div>
              <div><a href="javascript: void(0)" style="text-decoration: underline;" @click="onCreativeTagsClick(row)">{{
                  row.shortId
                }}</a></div>
            </div>
          </template>
          <template slot-scope="{ row }" slot="creativeUrl">
            <div @click="handleMediaPreview(row)">
              <img
                v-show="dialogType(row.creativeUrl) == 'image'"
                width="100%"
                :src="row.creativeUrl"
              />
              <video
                v-show="dialogType(row.creativeUrl) == 'video'"
                :src="row.creativeUrl"
                style="width: 100%"
              ></video>
            </div>
          </template>
          <template slot-scope="{ row }" slot="designer">
            <div>
              {{ designerChange(row) }}
            </div>
          </template>
          <template slot-scope="{ row }" slot="ads">
            <div>
              {{ countAds(row) }}
            </div>
          </template>
          <template slot-scope="{ row }" slot="ctr">
            <div>{{ row.ctr }}%</div>
          </template>
          <template slot-scope="{ row }" slot="cvr">
            <div>{{ row.cvr }}%</div>
          </template>
          <template slot-scope="{ row }" slot="onlineStatus">
            <span v-if="row.status !== 2 && row.onlineStatus === 1">违规</span>
            <span v-else-if="row.onlineStatus === 1">在线</span>
            <span v-else>未在线</span>
          </template>
          <template slot-scope="{type,size,row}" slot="menu">
            <el-tooltip content="查看" placement="top">
              <el-button size="small" icon="el-icon-view" type="text" @click="checkRow(row)"></el-button>
            </el-tooltip>
          </template>
          <template slot-scope="{row}" slot="impressions">
            <div>{{ thousandSeparator(row.impressions) }}</div>
          </template>
          <template slot-scope="{row}" slot="allExpend">
            <div>{{ thousandSeparator(row.allExpend) }}</div>
          </template>
          <template slot-scope="{row}" slot="install">
            <div>{{ thousandSeparator(row.install) }}</div>
          </template>
          <template slot-scope="{row}" slot="clicks">
            <div>{{ thousandSeparator(row.clicks) }}</div>
          </template>
        </avue-crud>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      title="预览"
      :visible="mediaPreviewDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :before-close="
        () => {
          mediaPreviewDialog.dialogVisible = false;
          if(mediaPreviewDialog.dialogType === 'video') {
            this.$refs.video.pause()
          }
        }
      "
      :append-to-body="true"
      style="text-align: center"
    >
      <img
        v-if="mediaPreviewDialog.dialogType === 'image'"
        :style="previewStyle()"
        :src="mediaPreviewDialog.previewUrl"
      />
      <video
        ref="video"
        v-if="mediaPreviewDialog.dialogType === 'video'"
        :src="mediaPreviewDialog.previewUrl"
        :style="previewStyle()"
        controls="controls"
      ></video>
    </el-dialog>

    <el-dialog
      :title="'素材：' + creativeInfoDialog.name"
      :visible="creativeInfoDialog.dialogVisible"
      width="80%"
      :modal-append-to-body="false"
      top="0px;"
      :close-on-click-modal="false"
      :append-to-body="true"
      style="text-align: center"
      :before-close="
        () => {
        creativeInfoDialog.dialogVisible = false;
        }
      "
    >
      <creative-info v-if="creativeInfoDialog.dialogVisible"
                     :creative-id="creativeInfoDialog.creativeId"></creative-info>
    </el-dialog>
    <creative-performance-detail width="80%" ref="creativePerformanceDetail"></creative-performance-detail>
  </basic-container>
</template>

<script>
import {
  add,
  getDesignerList,
  getDetail,
  getList,
  getSubmitter,
  remove,
  update,
  exportExcel,
} from "@/api/offer/creativeperformance";
import creativePerformanceDetail from '@/views/creativeReport/components/creativeperformancedetail'
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {getOutList} from '@/api/business/share'
import {getSysDictList} from "@/api/system/dict";
import {findObject} from "@/util/util";
import {createEventHandler} from "@/util/events";
import {mapGetters} from "vuex";
import Moment from "moment";
import creativeInfo from "./components/creativeInfo";

export default {
  components: {
    creativePerformanceDetail,
    creativeInfo
  },
  data() {
    let checkShortId = (rule, value, callback) => {
      const shortReg = /^\d{3,6}$/;
      if (value !== '' && !shortReg.test(value)) {
        callback(new Error('请输入3-6位数字!'))
      } else {
        callback()
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      selectList: [],
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      resultList: [],
      information: [],
      designerList: [],
      now: "",
      lastWeek: "",
      agencyTenantList: [],
      submitterList: [],
      countryList: [],
      platformList: [],
      nationList: [],
      tabName: 0,
      activeName: 0,
      queryForm: {
        shortId: '',
        name: '',
        localFilename: '',
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        designer: null,
        creativeId: null,
      },
      form: {},
      query: {},
      rules: {
        shortId: [{required: false, validator: checkShortId, trigger: 'change'}],
      },
      updateDateRange: [],
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      optionImg: {
        showSummary: true,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 60,
        dialogClickModal: false,
        defaultSort: {prop: 'allExpend', order: 'descending'},
        column: [
          {
            label: "素材",
            prop: "creativeUrl",
            rules: [
              {
                required: true,
                message: "请输入素材",
                trigger: "blur",
              },
            ],
            slot: true,
            fixed: true,
          },
          {
            label: "短Id",
            prop: "shortId",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            slot: true,
            fixed: true,
          },
          {
            label: "名称",
            prop: "performanceName",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
          },
          {
            label: "本地文件名",
            prop: "localFilename",
          },
          {
            label: "订单名",
            prop: "offerName",
          },
          {
            label: "状态",
            prop: "onlineStatus",
            dicData: [
              {label: "未在线", value: 0},
              {label: "在线", value: 1},
            ],
            slot: true,
          },
          {
            label: "设计师",
            prop: "designer",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            slot: true,
          },
          {
            label: "媒体",
            prop: "platform",
            multiple: true,
            dataType: 'string',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            searchMultiple: true,
          },
          {
            label: "投放地区",
            prop: "country",
            dataType: 'string',
            multiple: true,
            dicData: [],
            props: {
              label: "dictKey",
              value: "dictValue"
            },
          },
          {
            label: "在线天数",
            prop: "onlineDays",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "关联广告数",
            prop: "ads",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "花费",
            prop: "allExpend",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "曝光",
            prop: "impressions",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            width: 120,
            sortable: 'custom',
          },
          {
            label: "点击",
            prop: "clicks",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CTR",
            prop: "ctr",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
          {
            label: "安装",
            prop: "install",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CVR",
            prop: "cvr",
            rules: [
              {
                required: true,
                message: "请输入CVR",
                trigger: "blur",
              },
            ],
            slot: true,
            sortable: 'custom',
          },
        ],
      },
      optionVio: {
        showSummary: true,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 60,
        dialogClickModal: false,
        defaultSort: {prop: 'allExpend', order: 'descending'},
        column: [
          {
            label: "素材",
            prop: "creativeUrl",
            rules: [
              {
                required: true,
                message: "请输入素材",
                trigger: "blur",
              },
            ],
            slot: true,
            fixed: true,
          },
          {
            label: "短Id",
            prop: "shortId",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            fixed: true,
          },
          {
            label: "名称",
            prop: "performanceName",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
          },
          {
            label: "本地文件名",
            prop: "localFilename",
          },
          {
            label: "订单名",
            prop: "offerName",
          },
          {
            label: "状态",
            prop: "onlineStatus",
            dicData: [
              {label: "未在线", value: 0},
              {label: "在线", value: 1},
            ],
            slot: true,
          },
          {
            label: "设计师",
            prop: "designer",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
          },
          {
            label: "媒体",
            prop: "platform",
            multiple: true,
            dataType: 'string',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            searchMultiple: true,
          },
          {
            label: "投放地区",
            prop: "country",
            dataType: 'string',
            multiple: true,
            dicData: [],
            props: {
              label: "dictKey",
              value: "dictValue"
            },
          },
          {
            label: "在线天数",
            prop: "onlineDays",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "关联广告数",
            prop: "ads",
            rules: [
              {
                required: true,
                message: "请输入",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "花费",
            prop: "allExpend",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "曝光",
            prop: "impressions",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            width: 120,
            sortable: 'custom',
          },
          {
            label: "点击",
            prop: "clicks",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "时长",
            prop: "length",
            hide: true,
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
          },
          {
            label: "CTR",
            prop: "ctr",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "安装",
            prop: "install",
            rules: [
              {
                required: true,
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
          {
            label: "CVR",
            prop: "cvr",
            rules: [
              {
                required: true,
                message: "请输入CVR",
                trigger: "blur",
              },
            ],
            sortable: 'custom',
          },
        ],
      },
      imageData: [],
      videoData: [],
      imgSortList: [{name: 'allExpend', orderBy: 'desc'}],
      videoSortList: [{name: 'allExpend', orderBy: 'desc'}],
      mediaPreviewDialog: {
        dialogVisible: false,
        dialogType: "image", //image or video
        previewUrl: "",
      },
      creativeInfoDialog: {
        dialogVisible: false,
        name: '',
        creativeId: '',
      },
      isAdvSharedOffer: false,
    };
  },
  computed: {
    ...mapGetters(["permission", "offer", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.creativeperformance_add, false),
        viewBtn: this.vaildData(
          this.permission.creativeperformance_view,
          false
        ),
        delBtn: this.vaildData(
          this.permission.creativeperformance_delete,
          false
        ),
        editBtn: this.vaildData(
          this.permission.creativeperformance_edit,
          false
        ),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if (self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },

  created() {
    //window.addEventListener('keyup', this.submitForm) //监听键盘事件
    this.updateDateRange = [Moment().subtract(7,"days" ).format("yyyy-MM-DD"), Moment().subtract(1,"days").format("yyyy-MM-DD")];

    let self = this;
    this.eventHandler = createEventHandler("offerCenter").addListener(
      (event) => {
        if (
          event.message == "offerChanged" &&
          event.offerId &&
          event.offerId !== ""
        ) {
          self.offer = event.offerId;
          self.refresh();
          self.onLoad(self.page, {});
          self.updateIsAdvSharedOffer();
        }
      }
    );

    this.refresh();
    if (this.$route.query.creativeId) {
      this.activeName = this.$route.query.type === "图片" ? "0" : "1";
      if (this.$route.query.beginDate != null && this.$route.query.beginDate != '' && this.$route.query.endDate != null && this.$route.query.beginendDateDate != '') {
        this.updateDateRange = [this.$route.query.beginDate, this.$route.query.endDate];
      }
      this.queryForm.creativeId = this.$route.query.creativeId;
    }
    self.updateIsAdvSharedOffer();
    this.buildSearch();
  },
  methods: {
    thousandSeparator(num) {
      let s = num.toString();
      let div = s.indexOf('.');
      let sign = (num < 0) ? '-' : '';
      let intPart = (div == -1) ? s : s.substring(0, div);
      let dotPart = (div == -1) ? '' : s.substring(div);
      let finalIntPart = '';
      while (intPart.length > 3) {
        finalIntPart = ',' + intPart.substring(intPart.length - 3) + finalIntPart;
        intPart = intPart.substring(0, intPart.length - 3);
      }
      return sign + intPart + finalIntPart + dotPart;
    },
    summaryMethod({columns, data}) {
      const sums = [];
      let allExpendSum = 0;
      let impressionsSum = 0;
      let clicksSum = 0;
      let ctrSum = 0;
      let installSum = 0;
      let cvrSum = 0;
      let installCostSum = 0;
      if (data.length > 0) {
        data.forEach((row) => {
          allExpendSum += parseFloat(row.allExpend)
          impressionsSum += parseFloat(row.impressions)
          clicksSum += parseFloat(row.clicks)
          ctrSum += parseFloat(row.ctr)
          installSum += parseFloat(row.install)
          cvrSum += parseFloat(row.cvr)
          installCostSum += parseFloat(row.installCost)
        })
      }
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          if ([0].includes(index)) {
            sums[index] = '合计'
          } else if (column.label && column.label === "花费") {
            sums[index] = this.thousandSeparator(allExpendSum.toFixed(2))
          }else if (column.label && column.label === "曝光") {
            sums[index] = impressionsSum = this.thousandSeparator(impressionsSum.toFixed(2))
          }else if (column.label && column.label === "点击") {
            sums[index] = clicksSum = this.thousandSeparator(clicksSum.toFixed(2))
          }else if (column.label && column.label === "CTR") {
            sums[index] = ctrSum = this.thousandSeparator(ctrSum.toFixed(2))+ "%"
          }else if (column.label && column.label === "安装") {
            sums[index] = installSum = this.thousandSeparator(installSum.toFixed(2))
          }else if (column.label && column.label === "CVR") {
            sums[index] = cvrSum = this.thousandSeparator(cvrSum.toFixed(2)) + "%"
          }else if (column.label && column.label === "安装成本") {
            sums[index] = installCostSum = this.thousandSeparator(installCostSum.toFixed(2))
          } else {
            sums[index] = this.selectList.map(item => Number(item[column.property]));
          }
        });
      }
      return sums;
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.performTime.blur();
      if (!isShowSelectOptions) this.$refs.performCreateUser.blur();
      if (!isShowSelectOptions) this.$refs.performPlatform.blur();
    },
    previewStyle() {
      let height = window.innerHeight < 300 ? 300 : window.innerHeight - 160;
      return {
        maxWidth: "100%",
        maxHeight: height + "px",
      };
    },
    handleMediaPreview(row) {
      this.mediaPreviewDialog.previewUrl = row.creativeUrl + "?" + (row.updateTime ? row.updateTime.replace(/[ :-]*/gi, "") : 1234);
      this.mediaPreviewDialog.dialogType = row.type == 0 ? "image" : "video";
      this.mediaPreviewDialog.dialogVisible = true;
    },
    /**
     * 图片排序
     * @param val
     */
    sortImageChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.imgSortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.imgSortList = [];
      }
      this.onLoad(this.page);
    },
    /**
     * 视频排序
     * @param val
     */
    sortVideoChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.videoSortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.videoSortList = [];
      }
      this.onLoad(this.page);
    },
    setIsAdvSharedOfferChanged(val) {
      let self = this;
      self.isAdvSharedOffer = val;
      self.queryForm.createUser = null;
      self.queryForm.agencyTenantId = '';
      self.queryForm.agencyTenantIdList = [];
      let column = self.findObject(self.optionImg.column, 'designer');
      if (column && column != -1) {
        column.hide = self.isAdvSharedOffer;
      }
      column = self.findObject(self.optionImg.column, 'agencyTenantName');
      if (column && column != -1) {
        column.hide = !self.isAdvSharedOffer;
      }
      column = self.findObject(self.optionVio.column, 'designer');
      if (column && column != -1) {
        column.hide = self.isAdvSharedOffer;
      }
      column = self.findObject(self.optionVio.column, 'agencyTenantName');
      if (column && column != -1) {
        column.hide = !self.isAdvSharedOffer;
      }
      if (self.isAdvSharedOffer) {
        self.getAgencyTenantList();
      }
    },
    updateIsAdvSharedOffer() {
      let self = this;
      if (self.userInfo.is_agency == 0) {
        self.loadOfferInfo(self.offer, (offerInfo) => {
          if (offerInfo) {
            self.setIsAdvSharedOfferChanged(offerInfo.isShared == 1);
          } else {
            self.setIsAdvSharedOfferChanged(false);
          }
        });
      } else {
        self.setIsAdvSharedOfferChanged(false);
      }
    },
    loadOfferInfo(offerId, success) {
      if (offerId != null && offerId != '' && success) {
        getOfferDetail(offerId).then((res) => {
          success(res.data.data);
        }).catch(() => {
          success(null);
        });
      }
    },
    getAgencyTenantList() {
      getOutList(
        1,
        100,
        {offerId: this.offer},
      ).then(res => {
        this.agencyTenantList = res.data.data.records
      })
    },
    handleTabsClick(tab) {
      if (this.activeName != this.tabName) {
        this.page.currentPage = 1;
        this.tabName = this.activeName;
      }
    },
    refresh() {
      //refresh开始，这样写避免代码迁移太多
      /**
       * 调用设计师的字典
       * @type {string}
       */
      this.query.creativeId = null;
      this.query.offerId = this.offer;
      getDesignerList(this.offer).then((res) => {
        this.designerList = res.data.data;
      });
      getSysDictList("platforms,nation").then((map) => {
        this.platformList = map['platforms'];
        this.nationList = map['nation'];
        let column = findObject(this.optionImg.column, 'platform', 'prop');
        if (column != null) {
          column.dicData = this.platformList;
        }
        column = findObject(this.optionImg.column, 'country', 'prop');
        if (column != null) {
          column.dicData = this.nationList;
        }
        column = findObject(this.optionVio.column, 'platform', 'prop');
        if (column != null) {
          column.dicData = this.platformList;
        }
        column = findObject(this.optionVio.column, 'country', 'prop');
        if (column != null) {
          column.dicData = this.nationList;
        }
      });
      getSubmitter(this.offer).then((res) => {
        this.submitterList = res.data.data;
      });
    },
    /**
     * 用来转换设计师id （方法）
     */
    designerChange(row) {
      let designers = row.designer.split(",");
      let designerList = this.designerList;
      let name = [];
      for (let i in designerList) {
        let designerId = designerList[i].id;
        let designerName = designerList[i].realName;
        for (let j in designers) {
          let designer = designers[j];
          if (designer === designerId) {
            name.push(designerName);
          }
        }
      }
      return name.join(",");
    },
    /**
     * 统计当前素材跑了多少个广告
     * @param row
     * @returns {string}
     */
    countAds(row) {
      let adsArr = row.ads.split(",");
      let res = [...new Set(adsArr)];
      return res.length;
    },
    buildSearch() {
      let query = {...this.queryForm};
      delete query.nationList;
      if (this.updateDateRange != null && this.updateDateRange.length == 2) {
        query.beginDate = this.updateDateRange[0];
        query.endDate = this.updateDateRange[1];
      } else {
        query.beginDate = "";
        query.endDate = "";
      }
      query.country = this.queryForm.nationList.join(',')
      this.query = query;
    },
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buildSearch();
          this.page.currentPage = 1;
          this.onLoad(this.page);
        }
      });
    },
    resetSearch() {
      this.queryForm = {
        shortId: '',
        name: '',
        localFilename: '',
        platform: null,
        beginDate: null,
        endDate: null,
        nationList: [],
        designer: null,
        creativeId: null,
      };
      this.updateDateRange = [];
      this.submitForm();
    },
    exportExcel() {
      const type = this.activeName;
      let sortList = (this.activeName == 0) ? this.imgSortList : this.videoSortList;
      let params = {}
      this.$confirm("是否导出数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        exportExcel(
          this.page.currentPage,
          this.page.pageSize,
          Object.assign({}, params, {offerId: this.offer}, this.query, {sortList: JSON.stringify(sortList)}),
          type
        ).then(res => {
          console.log(res)
          let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          let url = window.URL.createObjectURL(new Blob([res.data]))
          let link = document.createElement("a")
          link.style.display = "none"
          link.href = url
          link.download = filename
          document.body.appendChild(link)
          link.click()
        })
      })
    },
    dialogType(val) {
      let type;
      let urlTail = val.split(".")[val.split(".").length - 1];
      let imgList = ["jpg", "jpeg", "png", "gif", "bmp"];
      let videoList = ["mp4", "mov", "avi", "mp3", "ogg", "rmvb", "mkv"];
      if (imgList.includes(urlTail)) {
        type = "image";
      } else if (videoList.includes(urlTail)) {
        type = "video";
      }
      return type;
    },
    checkRow(row) {
      this.$refs.creativePerformanceDetail.showDialog({creativeId: row.creativeId, shortId: row.shortId, performanceName: row.performanceName});
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.resetSearch();
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      const type = this.activeName;
      let sortList = (this.activeName == 0) ? this.imgSortList : this.videoSortList;
      getList(
        this.page.currentPage,
        this.page.pageSize,
        Object.assign({}, params, {offerId: this.offer}, this.query, {sortList: JSON.stringify(sortList)}),
        type
      ).then((res) => {
        let data = res.data.data;
        this.page.total = data.total;
        this.resultList = res.data.data.records;
        for (let i = 0; i < this.resultList.length; i++) {
          if (this.resultList[i].country != null && this.resultList[i].country != '') {
            let countryList = this.resultList[i].country.split(',');
            let set = new Set();
            countryList.forEach(c => {
              if (c != '') {
                set.add(c);
              }
            });
            this.resultList[i].country = Array.from(set).join(',');
          }
        }
        if (type === "0") {
          this.imageData = this.resultList;
        } else {
          this.videoData = this.resultList;
        }
        this.loading = false;
        this.selectionClear();
      });
    },
    onCreativeTagsClick(row) {
      let self = this;

      self.$nextTick(() => {
        self.creativeInfoDialog.name = row.name;
        self.creativeInfoDialog.creativeId = row.id;
        self.creativeInfoDialog.dialogVisible = true;
      });

    },
  },
};
</script>

<style scoped lang="scss">
.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}

.search-form {

  /deep/ .el-form-item {
    margin-bottom: 0;
  }

}
/deep/ .el-table__body-wrapper{
  z-index:2
}
/deep/ .search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 6px;
}
.el-select-dropdown.is-multiple .el-select-dropdown__item.selected::after ::v-deep{
  position: absolute;
  right: 3px;
  font-family: element-icons;
  content: "\e6da";
  font-size: 12px;
  font-weight: 700;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
</style>
